import Vue from 'vue';
import VueResource from 'vue-resource';
import bus from '../../../static/js/bus.js';
Vue.use(VueResource)
let webSocket_svr=null
//websoket
let SocketTask = null
startApp()
//获取配置文件
async function startApp() {
	if(process.env.NODE_ENV=='development'){
		let data=await Vue.http.get('/static/config.json')
		webSocket_svr=JSON.parse(data.bodyText).WEBSOCKET_URL
	}else{
		// let data=await Vue.http.get('./static/config.json')
		// webSocket_svr=JSON.parse(data.bodyText).WEBSOCKET_URL
		webSocket_svr="ws://135.0.64.217:8080/sealTransferApi/callback/ws"
	}
	return webSocket_svr
}


//创建和关闭websocket  true为创建false为关闭
function lz_websoket(onoff) {
	if(onoff){
		console.log(webSocket_svr);
		//先关闭上一个在连接
		try {
			SocketTask.close()
		} catch (e) {
			//TODO handle the exception
		}
	}
	// 创建websocket连接
	SocketTask = new WebSocket(webSocket_svr);
	// 监听打开
	SocketTask.onopen=function(event){
		console.log('监听打开',event);
	}
	// 监听关闭
	SocketTask.onclose=function(event){
		console.log('监听关闭',event);
	}
	//监听异常
	SocketTask.onerror=function(event){
		console.log('监听异常',event);
	}
	//监听服务器发送的消息
	SocketTask.onmessage=function(event){
		console.log('监听服务器发送的消息',event.data);
		bus.$emit('SocketTask_onmessage',event.data)
	}
}
function send(msg) {
	SocketTask.send(msg)
}

export default {
	lz_websoket,
	send,
}
